package com.mailanalyzer.analyzer.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.Message;

import com.mailanalyzer.analyzer.Analyzer;
import com.mailanalyzer.dto.FlightData;
import com.mailanalyzer.dto.Way;

/**
 * 
 * @author anibal.kolker
 *
 */
public class RyanairAnalyzer implements Analyzer {

	private static final Pattern intsOnly = Pattern.compile("\\d+(\\.\\d{1,2})");

	@Override
	public FlightData handle(Message message, String text) {
		FlightData data = new FlightData();

		StringReader reader = new StringReader(text);
		BufferedReader bf = new BufferedReader(reader);
		String line = null;
		String lineBefore = "";

		try {
			while( (line = bf.readLine()) != null ){
				if(line==null || line.trim().length()==0)
					continue;

				//Price
				if( line.contains("Total Paid") ){
					Matcher makeMatch = intsOnly.matcher(line);
					makeMatch.find();
					data.setPrice(Float.valueOf(makeMatch.group()));
				}
				//Going to
				if( lineBefore.trim().equalsIgnoreCase("GOING OUT")){
					data.setGoingTo(new Way(line.substring(6,line.indexOf(" to ")).trim(),line.substring(line.indexOf(" to ")+4).trim()));
				}
				//Coming back
				if( lineBefore.trim().equalsIgnoreCase("COMING BACK")){
					data.setComingBack(new Way(line.substring(6,line.indexOf(" to ")).trim(),line.substring(line.indexOf(" to ")+4).trim()));
				}

				//save line as before
				lineBefore = line;

			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return data;
	}

	@Override
	public boolean canHandle(Message message) {
		try{return message.getFrom()[0].toString().indexOf("itinerary@ryanair.com")!=-1;}
		catch(Exception e){return false;}
	}

}
